package com.huatai.bi.websocket;

import com.alibaba.fastjson.JSONObject;
import com.huatai.bi.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @program: ganghua
 * @description: ce
 * @author: songxiude
 * @create: 2024-09-19 11:09
 **/
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{sid}/{topic}/{ts}", configurator = WebSocketConfig.class, encoders = {EncoderServer.class})
public class WebSocket {
	public static ConcurrentHashMap<String, Session> electricSocketMap = new ConcurrentHashMap<String, Session>();
	/**
	 * 此处是解决无法注入的关键
	 */
	private static ApplicationContext applicationContext;


	public static void setApplicationContext(ApplicationContext applicationContext) {
		WebSocket.applicationContext = applicationContext;
	}

	@OnOpen
	public void open(@PathParam("sid") String sid, @PathParam("topic") String topic, @PathParam("ts") String ts, Session session) {
		electricSocketMap.put(sid + "_" + topic + "_" + ts, session);
		log.info("websocket连接成功,用户编号为:" + sid + "_" + topic + "_" + ts);

	}

	@OnClose
	public void close(@PathParam("sid") String sid, @PathParam("topic") String topic ,@PathParam("ts") String ts, Session session) {
		if (electricSocketMap.containsKey(sid + "_" + topic + "_" + ts)) {
			electricSocketMap.remove(sid + "_" + topic + "_" + ts);
			log.info("该连接已断开：" + sid + "_" + topic + "_" + ts);
		}
	}

	/**
	 * message:{toUserId,msgInfo,msgType}
	 * 如果发送状态为1:表示单独返送
	 * 如果发送状态为2:表示群体发送
	 *
	 * @param message
	 * @param session
	 */
	@OnMessage
	public void onMessage(@PathParam("sid") String sid, String message, Session session) {
		WebSocketService websocketService = applicationContext.getBean(WebSocketService.class);
//		MessageResult messageResult = JSONObject.parseObject(message, MessageResult.class);
//		websocketService.sendAlls(messageResult);

//		if (messageResult.getToUserId() != null) {
//			sid = messageResult.getToUserId();
//		}
//
//		if (electricSocketMap.containsKey(sid)) {
//			if (messageResult.getMsgType() == 1) {
//				session = electricSocketMap.get(sid);
//				sendMsg(session, messageResult);
//			} else {
//				Set<Map.Entry<String, Session>> entries = electricSocketMap.entrySet();
//				for (Map.Entry<String, Session> entry : entries) {
//					sendMsg(entry.getValue(), messageResult);
//				}
//			}
//		} else {
//			if (messageResult.getMsgType() == 1) {
//				websocketService.send(sid, messageResult);
//			} else {
//				websocketService.sendAll(electricSocketMap, messageResult);
//			}
//		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
		System.out.println("发生错误");
	}

	/**
	 * @param session
	 * @param message 消息结果集
	 */
	public static void sendMsg(Session session, MessageResult message) {
		try {
			session.getBasicRemote().sendObject(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 群发消息
	 *
	 * @param message 消息内容
	 */
	private void sendAll(MessageResult message) {
		WebSocketService websocketService = applicationContext.getBean(WebSocketService.class);
		websocketService.sendAll(electricSocketMap, message);
	}

}
